const Router = require('koa-router');
const messageService = require('../services/messageService');
const { authenticateToken, authorize } = require('../middlewares/auth.middleware');

const router = new Router();

/**
 * 消息相关路由
 */

// 创建消息
router.post('/', authenticateToken, async (ctx) => {
  try {
    const userId = ctx.state.userId;
    const messageData = ctx.request.body;
    
    const message = await messageService.createMessage(messageData, userId);
    
    ctx.status = 201;
    ctx.body = {
      success: true,
      message: '消息创建成功',
      data: message
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 获取消息列表
router.get('/', authenticateToken, async (ctx) => {
  try {
    const { 
      page = 1, 
      limit = 20, 
      type, 
      status, 
      read, 
      startDate, 
      endDate,
      receiverId,
      senderId
    } = ctx.query;
    
    const filters = {
      type,
      status,
      read: read !== undefined ? read === 'true' : undefined,
      startDate,
      endDate,
      receiverId,
      senderId
    };
    
    // 过滤掉undefined值
    Object.keys(filters).forEach(key => {
      if (filters[key] === undefined) {
        delete filters[key];
      }
    });
    
    const result = await messageService.getMessages(
      filters, 
      parseInt(page), 
      parseInt(limit)
    );
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      data: result.messages,
      pagination: result.pagination
    };
  } catch (error) {
    ctx.status = error.status || 500;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 获取消息详情
router.get('/:messageId', authenticateToken, async (ctx) => {
  try {
    const messageId = ctx.params.messageId;
    const message = await messageService.getMessageById(messageId);
    
    // 检查权限：只有发送者、接收者或管理员可以查看消息
    const userId = ctx.state.userId;
    if (message.sender._id.toString() !== userId && 
        message.receiver.toString() !== userId && 
        ctx.state.role !== 'admin') {
      ctx.status = 403;
      ctx.body = {
        success: false,
        message: '无权限查看此消息'
      };
      return;
    }
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      data: message
    };
  } catch (error) {
    ctx.status = error.status || 404;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 更新消息
router.put('/:messageId', authenticateToken, async (ctx) => {
  try {
    const messageId = ctx.params.messageId;
    const updateData = ctx.request.body;
    const userId = ctx.state.userId;
    
    const updatedMessage = await messageService.updateMessage(
      messageId, 
      updateData, 
      userId
    );
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      message: '消息更新成功',
      data: updatedMessage
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 删除消息
router.delete('/:messageId', authenticateToken, async (ctx) => {
  try {
    const messageId = ctx.params.messageId;
    const userId = ctx.state.userId;
    
    await messageService.deleteMessage(messageId, userId);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      message: '消息删除成功'
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 标记消息为已读
router.put('/:messageId/read', authenticateToken, async (ctx) => {
  try {
    const messageId = ctx.params.messageId;
    const userId = ctx.state.userId;
    
    const updatedMessage = await messageService.markAsRead(messageId, userId);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      message: '消息已标记为已读',
      data: updatedMessage
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 批量标记消息为已读
router.put('/batch/read', authenticateToken, async (ctx) => {
  try {
    const { messageIds } = ctx.request.body;
    const userId = ctx.state.userId;
    
    if (!Array.isArray(messageIds) || messageIds.length === 0) {
      ctx.status = 400;
      ctx.body = {
        success: false,
        message: '请提供有效的消息ID列表'
      };
      return;
    }
    
    // 批量标记消息为已读
    const promises = messageIds.map(messageId => 
      messageService.markAsRead(messageId, userId)
    );
    
    await Promise.all(promises);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      message: `成功标记 ${messageIds.length} 条消息为已读`
    };
  } catch (error) {
    ctx.status = error.status || 400;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 获取未读消息数量
router.get('/unread/count', authenticateToken, async (ctx) => {
  try {
    const userId = ctx.state.userId;
    const count = await messageService.getUnreadCount(userId);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      data: { count }
    };
  } catch (error) {
    ctx.status = error.status || 500;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

// 获取消息统计信息
router.get('/stats', authenticateToken, async (ctx) => {
  try {
    const userId = ctx.state.userId;
    const { startDate, endDate } = ctx.query;
    
    // 这里可以实现消息统计逻辑，例如按类型统计消息数量等
    // 暂时返回简单的统计信息
    const unreadCount = await messageService.getUnreadCount(userId);
    
    ctx.status = 200;
    ctx.body = {
      success: true,
      data: {
        unreadCount,
        period: startDate && endDate ? `${startDate} 至 ${endDate}` : '全部'
      }
    };
  } catch (error) {
    ctx.status = error.status || 500;
    ctx.body = {
      success: false,
      message: error.message
    };
  }
});

module.exports = router;